package com.vtmer.exception;

import com.alibaba.druid.sql.visitor.functions.Reverse;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.vtmer.result.ResultVo;
import com.vtmer.result.impl.ResultCode;
import org.apache.ibatis.reflection.ReflectionException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @author Colin_Knight
 * @create 2022/9/25 20:07
 */
@RestControllerAdvice
public class ControllerExceptionAdvice {

    @ExceptionHandler({BindException.class})
    public ResultVo<String> methodArgumentNotValidExceptionHandler(BindException e) {
        // 从异常对象中拿到ObjectError对象

        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new ResultVo(ResultCode.VALIDATE_ERROR, objectError.getDefaultMessage());
    }

    @ExceptionHandler({ReflectionException.class})
    public ResultVo<String> reflectionExceptionHandler(ReflectionException e){
        String message = e.getMessage();
        return new ResultVo<>(ResultCode.INVOCATION_TARGET_EXCEPTION,message);
    }

    @ExceptionHandler({IllegalArgumentException.class})
    public ResultVo<String> illegalArgumentExceptionHandler(Exception e){
        return new ResultVo(ResultCode.NO_USER, e.getMessage());
    }

    @ExceptionHandler({MybatisPlusException.class})
    public ResultVo<String> mybatisPlusExceptionHandler(Exception e){
        return new ResultVo(ResultCode.NO_USER, null);
    }

    @ExceptionHandler(NumberFormatException.class)
    public ResultVo<String> numberFormatExceptionHandler(NumberFormatException e){
        return new ResultVo(ResultCode.NUMBER_FORMAT_EXCEPTION,e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResultVo<String> baseExceptionHandler(Exception e){
        return new ResultVo<>(ResultCode.SERVICE_ERROR,e.getMessage());
    }

}
